using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Drawing;
using Microsoft.SharePoint;
using net.windward.api.csharp;
using net.windward.utils.ado;
using System.IO;
using System.Net;
using System.Xml;
using System.Data.Common;
using net.windward.tags;
using net.windward.util;
using log4net;

namespace ArrowWebParts
{
    public class DashboardWebPart : WebPart
    {
        #region fields

        private string displayUrl = "about:blank";
        [Personalizable(PersonalizationScope.User),
       WebBrowsable(false)]
        //WebDisplayName("URL"),
        //WebDescription("Set the URL to display here!")]
        //System.ComponentModel.CategoryAttribute("")]
        public string DisplayUrl
        {
            get { return displayUrl; }
            set { displayUrl = value; }
        }

        private int refreshTime = 0;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        //WebDisplayName("Refresh timer (seconds)"),
        //WebDescription("Set the amount of time between automatic refreshes!")]
        public int RefreshTime
        {
            get { return refreshTime; }
            set { refreshTime = value; }
        }

        private int frameHeight = 0;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        //WebDisplayName("Widget height (pixels)"),
        //WebDescription("Set the height of the dashboard widget!")]
        public int FrameHeight
        {
            get { return frameHeight; }
            set { frameHeight = value; }
        }

        private bool scrollbarDisplay = true;
        [Personalizable(PersonalizationScope.User),
        WebBrowsable(false)]
        public bool ScrollbarDisplay
        {
            get { return scrollbarDisplay; }
            set { scrollbarDisplay = value; }
        }

        private Guid siteGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid SiteGuid
        {
            get { return siteGuid; }
            set { siteGuid = value; }
        }

        private Guid docLibGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid DocLibGuid
        {
            get { return docLibGuid; }
            set { docLibGuid = value; }
        }

        private Guid fileGuid = Guid.Empty;
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Guid FileGuid
        {
            get { return fileGuid; }
            set { fileGuid = value; }
        }

        private Dictionary<string, string> dashboardVariables = new Dictionary<string, string>();
        [Personalizable(PersonalizationScope.User),
         WebBrowsable(false)]
        public Dictionary<string, string> DashboardVariables
        {
            get { return dashboardVariables; }
            set { dashboardVariables = value; }
        }

        private string id1;
        /// <summary>
        /// the log
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(DashboardWebPart));

        #endregion

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (log.IsDebugEnabled)
                log.Debug("creating child controls");

            try
            {
                // read in license from web.config
                ArrowUtils.InitializeArrow(string.Concat(Page.Request.PhysicalApplicationPath, "\\web.config"));
            }
            catch (LicenseException lex)
            {
                ArrowUtils.LogFatalException(log, lex);
                Controls.Add(new LiteralControl(string.Format("License Error: {0}", lex.Message)));
                return;
            }

            try
            {
                id1 = this.UniqueID + "WRFrame";

                //Controls.Add(new LiteralControl("<input type=\"button\" value=\"Reload Page\" onClick=\"document.WRFrameName.location.reload()\"/>"));

                //Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function changeSrc() { document.frames['" + idToUse + "'].location.href=document.getElementById(\"txtBox\").value; }</script><br/>"));
                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> var general_height_" + id1 + "=" + FrameHeight + "; function calcHeight" + id1 + "() { var the_height=document.getElementById(\"" + id1 + "\").contentWindow.document.body.scrollHeight;  if(general_height_" + id1 + "<=0){general_height_" + id1 + "=the_height+35;} document.getElementById(\"" + id1 + "\").height=general_height_" + id1 + ";}</script>"));
                //Controls.Add(new LiteralControl("<script type=\"text/javascript\"> var general_height=-1; function calcHeight" + idToUse + "() { var the_height=document.getElementById(\"" + idToUse + "\").contentWindow.document.body.scrollHeight; document.getElementById(\"" + idToUse + "\").height=the_height;}</script>"));
                Controls.Add(createFrameLiteralControl(id1, DisplayUrl, ScrollbarDisplay));

                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function setRefreshTimer" + id1 + "() { setTimeout('refreshFrame" + id1 + "()'," + (RefreshTime * 1000).ToString() + ") } </script>")); // function to set timer
                //Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function refreshFrame" + idToUse + "() { document.frames['" + idToUse + "'].location.reload(); setRefreshTimer" + idToUse + "(); }</script>")); // function to refresh
                Controls.Add(new LiteralControl("<script type=\"text/javascript\"> function refreshFrame" + id1 + "() { if(document.frames['" + id1 + "'].location.href==\"about:blank\") {document.frames['" + id1 + "'].location.href=\"" + DisplayUrl + "\"; } else {document.frames['" + id1 + "'].location.reload();} setRefreshTimer" + id1 + "(); }</script>")); // function to refresh
                if (refreshTime > 0)
                    Controls.Add(new LiteralControl("<script type=\"text/javascript\"> mytime = setTimeout('refreshFrame" + id1 + "()'," + (RefreshTime * 1000).ToString() + ") </script>")); // start the refresh
                //Controls.Add(new LiteralControl("<script type=\"text/javascript\"> mytime = setTimeout('document.WRFrameName.location.reload()',3000) </script>")); // start the refresh
            }
            catch (Exception ex)
            {
                ArrowUtils.LogFatalException(log, ex);
                Controls.Clear();
                Controls.Add(new LiteralControl(string.Format("There was an error creating the dashboard web part: {0}", ex.Message)));
                return;
            }

            if (log.IsDebugEnabled)
                log.Debug("Finished creating child controls.");
        }

        public override EditorPartCollection CreateEditorParts()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating editor parts.");

            try
            {
                List<EditorPart> editorParts = new List<EditorPart>(1);
                EditorPart part = new DashboardEditorPart();
                part.ID = this.ID + "_dashboardEditor";
                editorParts.Add(part);
                EditorPartCollection baseParts = base.CreateEditorParts();

                if (log.IsDebugEnabled)
                    log.Debug("Finished creating editor parts.");

                return new EditorPartCollection(baseParts, editorParts);
            }
            catch (Exception ex)
            {
                ArrowUtils.LogFatalException(log, ex);
                // throw the exception, otherwise the error goes unknown except that arrow editor parts are missing
                //return new EditorPartCollection();
                throw;
            }
        }

        #region iframe

        private LiteralControl createFrameLiteralControl(string id, string url, bool displayScrollbar)
        {
            if (displayScrollbar == true)
                return new LiteralControl("<iframe ID=\"" + id + "\" src=\"" + url + "\" runat=\"server\" width=\"100%\" height=\"0px\" onLoad=\"calcHeight" + id + "();\" frameborder=\"0\"> </iframe>");
            else
                return new LiteralControl("<iframe ID=\"" + id + "\" src=\"" + url + "\" runat=\"server\" width=\"100%\" height=\"0px\" onLoad=\"calcHeight" + id + "();\" frameborder=\"0\" scrolling=\"no\" > </iframe>");
            //return new LiteralControl("<iframe ID=\"WRFrame\" name=\"WRFrameName\" src=\"" + DisplayUrl + "\" runat=\"server\" width=\"100%\" height=\"400px\" onLoad=\"calcHeight();\"> </iframe>");
        }

        #endregion
    }
}
